<?php

namespace App\Jobs;

use App\Models\Archive\Migration\OperationLogsTable;
use App\Models\Archive\OperationLog;
use App\Models\Auth\User;
use App\Models\Common\ArchiveCatalog;
use App\Models\Common\Constant;
use App\Models\ParkingLot\ParkingLot;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Psr\Log\LoggerInterface;

class LoggingOperationLog implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $type;
    protected $logContent;
    protected $parkingLotID;
    protected $source;
    protected $ip;
    protected $keyword;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, string $type, string $logContent, string $ip, string $parkingLotID = null, string $keyword = null, string $source = Constant::SOURCE_ADMIN)
    {
        $this->ip = $ip;
        $this->user = $user;
        $this->type = $type;
        $this->source = $source;
        $this->logContent = $logContent;
        $this->parkingLotID = $parkingLotID;
        $this->keyword = $keyword ?: '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $user = $this->user;
        $parkingLotID = $this->parkingLotID;

        try {
            $tableName = OperationLog::getTableName();
            if (!ArchiveCatalog::where('name', $tableName)->exists()) {
                RunArchiveMigration::dispatch((new OperationLogsTable()), $tableName)->onQueue(Constant::QUEUE_SINGLE);
                sleep(2);
            }

            $operationLog = new OperationLog;
            $operationLog->setTable($tableName);

            $operationLog->loggable_id = $user->id;
            $operationLog->loggable_type = get_class($user);
            $operationLog->loggable_name = $user->name;

            if ($parkingLotID && ($parkingLot = ParkingLot::find($parkingLotID))) {
                $operationLog->parking_lot_id = $parkingLotID;
                $operationLog->parking_lot_name = $parkingLot->name;
            }

            $operationLog->parking_lot_id = strval($operationLog->parking_lot_id);
            $operationLog->source = $this->source;
            $operationLog->type = $this->type;
            $operationLog->content = $this->logContent;
            $operationLog->login_ip = @ip2long($this->ip);
            $operationLog->keyword = $this->keyword ?: '';

            $operationLog->save();
        } catch (\Throwable $exception) {
            app(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'trigger' => '操作记录脚本']);
        }
    }
}
